import React, { createContext, useContext, useState, useCallback } from 'react';
import Message, { MessageProps } from './Message';

interface MessageContextType {
  showMessage: (options: Omit<MessageProps, 'visible' | 'onClose'>) => void;
  hideMessage: () => void;
}

const MessageContext = createContext<MessageContextType | null>(null);

export const useMessage = () => {
  const context = useContext(MessageContext);
  if (!context) {
    throw new Error('useMessage must be used within MessageProvider');
  }
  return context;
};

interface MessageProviderProps {
  children: React.ReactNode;
}

export const MessageProvider: React.FC<MessageProviderProps> = ({ children }) => {
  const [messageState, setMessageState] = useState<{
    visible: boolean;
    props: Omit<MessageProps, 'visible' | 'onClose'>;
  }>({
    visible: false,
    props: {
      type: 'info',
      message: '',
      duration: 3000
    }
  });

  const showMessage = useCallback((options: Omit<MessageProps, 'visible' | 'onClose'>) => {
    setMessageState({
      visible: true,
      props: {
        duration: 3000,
        ...options
      }
    });
  }, []);

  const hideMessage = useCallback(() => {
    setMessageState(prev => ({
      ...prev,
      visible: false
    }));
  }, []);

  const value = {
    showMessage,
    hideMessage
  };

  return (
    <MessageContext.Provider value={value}>
      {children}
      <Message
        {...messageState.props}
        visible={messageState.visible}
        onClose={hideMessage}
      />
    </MessageContext.Provider>
  );
};

// 便捷的消息函数
export const useMessageHelpers = () => {
  const { showMessage } = useMessage();

  return {
    success: (message: string, duration?: number) => 
      showMessage({ type: 'success', message, duration }),
    error: (message: string, duration?: number) => 
      showMessage({ type: 'error', message, duration }),
    warning: (message: string, duration?: number) => 
      showMessage({ type: 'warning', message, duration }),
    info: (message: string, duration?: number) => 
      showMessage({ type: 'info', message, duration })
  };
};